import React, { useState } from 'react';
import { Button, Checkbox, Form, Input, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import Request from '../../Utils/Request';

function Login() {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();
  const [isLogin, setIsLogin] = useState(true);

  // 切换登录/注册
  const toggleLogin = () => {
    form.resetFields();
    setIsLogin(!isLogin);
  };

  // 校验密码强度
  const checkPwd = val => {
    let strength = 0;

    // 正则表达式用于检查密码强度
    const regexs = [
      /[a-z]/, // 小写字母
      /[A-Z]/, // 大写字母
      /[0-9]/, // 数字
      /[\~\`\!\@\#\$\%\^\&\*\(\)\-\_\+\=\{\[\}\]\:\;\"\'\,\.<>\/\?]/, // 特殊字符
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[\~\`\!\@\#\$\%\^\&\*\(\)\-\_\+\=\{\[\}\]\:\;\"\'\,\.<>\/\?]).{8,}$/ // 大小写字母、数字和特殊字符的组合，且长度至少为8
    ];

    regexs.forEach(regex => {
      if (regex.test(val)) {
        strength++;
      }
    });

    return strength;
  };

  // 提交
  const onFinish = async values => {
    const options = {
      url: isLogin ? 'login' : 'register',
      method: 'post',
      data: values
    };
    const result = await Request(options);
    const { code, data } = result.data;
    console.log(data);
    if (code === 200) {
      messageApi.success(isLogin ? '登录成功' : '注册成功');
      if (isLogin) {
        localStorage.setItem('token', data.token);
        localStorage.setItem('username', data.name);
        localStorage.setItem('userId', data.id);
        localStorage.setItem('password', data.password);
        localStorage.setItem('remember', values.remember);
        form.resetFields();
        navigate('/main');
      } else {
        toggleLogin();
      }
    }
  };

  return (
    <div className='w-full h-full flex justify-end items-center relative bg-gray-100'>
      {contextHolder}
      <div className='container w-96 flex flex-col items-center justify-center shadow-xl bg-white rounded-md  mr-10 ml-10 px-10 py-10'>
        <Form
          form={form}
          labelCol={{ span: 8 }}
          onFinish={onFinish}
          autoComplete='off'
          initialValues={
            JSON.parse(localStorage.remember)
              ? {
                username: localStorage.username,
                password: localStorage.password,
                remember: JSON.parse(localStorage.remember)
              }
              : {}
          }
        >
          <Form.Item
            label='用户名'
            name='username'
            rules={[
              {
                required: true,
                message: '请输入邮箱!'
              },
              {
                type: 'email',
                message: '请输入正确的邮箱格式!'
              }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name='password'
            label='密码'
            rules={[
              {
                required: true,
                message: '请输入您的密码!'
              },
              () => ({
                validator(_, value) {
                  const flag = checkPwd(value);
                  // 1代表较弱 2代表中等 3代表较强
                  if (flag === 1) {
                    return Promise.reject(new Error('密码强度较弱，请输入更复杂的密码'));
                  } else if (flag === 2) {
                    return Promise.reject(new Error('密码强度中等，请输入更复杂的密码'));
                  } else {
                    return Promise.resolve();
                  }
                }
              })
            ]}
            hasFeedback
          >
            <Input.Password />
          </Form.Item>
          {!isLogin && (
            <Form.Item
              name='confirm'
              label='确认密码'
              dependencies={['password']}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: '请确认密码!'
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('您输入的的与新密码不匹配!'));
                  }
                })
              ]}
            >
              <Input.Password />
            </Form.Item>
          )}
          {isLogin && (
            <Form.Item>
              <div className='w-full flex justify-between items-center'>
                <Form.Item
                  className='flex-auto mb-0'
                  name='remember'
                  valuePropName='checked'
                  wrapperCol={{
                    offset: 2,
                    span: 16
                  }}
                  initialValue={false}
                >
                  <Checkbox className='text-blue-500'>记住我</Checkbox>
                </Form.Item>

                <span className='cursor-pointer text-blue-500' onClick={toggleLogin}>
                  注册
                </span>
              </div>
            </Form.Item>
          )}
          <Form.Item
            className='mb-0'
            wrapperCol={{
              offset: 0,
              span: 24
            }}
          >
            {isLogin ? (
              <Button type='primary' htmlType='submit' block>
                登录
              </Button>
            ) : (
              <Button type='primary' htmlType='submit' block>
                注册
              </Button>
            )}
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}

export default Login;
